<template>
	<view class="container">
		<view class="inaver _30f2b4d">
			<view class="video_box">
				<video id="myVideo" :src="$com.imageOSS('anli/m17285427850005563.mp4')" :controls="false"
					style="width: 100%; height: 100%" object-fit="cover" :show-center-play-btn="false" autoplay loop
					muted @ended="ended"></video>
			</view>
			<!-- <view class="poa_play" v-if="!isShowPlayButton">
				<van-icon name="/static/img/play.png" size="40" color="#fff" @tap.native="onPlay" />
			</view> -->
			<view class="left _30f2b4d" @tap.stop.prevent="gohome">
				<image class="icon _30f2b4d" src="/static/img/home-gray.png"
					:style="'width:50rpx; height:50rpx; margin-top: ' + navbar.top + 'px;position: absolute;'" />
			</view>
		</view>
		<view class="login_box">
			<!-- kejulogo -->
			<view :style="'text-align:center;margin-top:' + (loginSwitchType == 1 ? '40' : '16') + 'rpx;'">
				<image :src="$com.imageOSS('xuqiu/m17285436060008303.png')"
					style="width: 300rpx; height: 104rpx; text-align: center" />
			</view>
			<view class="topbar-selectDate" :style="'margin-top: ' + (loginSwitchType == 1 ? '58' : '24') + 'rpx;'">
				<!-- 登录提交 -->
				<view class="submit-layer">
					<view class="weixin" :style="'display: ' + (loginSwitchType == 1 ? 'block' : 'none')">
						<!-- #ifdef MP-WEIXIN -->
						<view class="login_btn phone_btn" v-if="radio==1">
							手机号码快捷登录
							<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
								class="control-button"></button>
						</view>
						<view class="login_btn phone_btn" v-else @click="noSelectRadio">
							手机号码快捷登录
						</view>
						<!-- #endif -->
						<!-- #ifdef MP-TOUTIAO -->
						<view class="login_btn phone_btn" data-eventsync="true" @click="getUserProfile">抖音授权登录</view>
						<!-- #endif -->
						<view style="margin-top: 10px; display: none">
							<van-button block round color="#323233" plain @click="loginSwitch(2)">手机验证码登入</van-button>
						</view>
						<view class="login_btn number_btn" @tap="loginSwitch(3)">账号密码登入</view>
					</view>

					<template v-if="loginSwitchType == 3">
						<uni-forms ref="userFormRef" :modelValue="userForm" :rules="rules">
							<uni-forms-item name="userName" required>
								<uni-easyinput type="text" v-model="userForm.userName" placeholder="请输入用户名" />
							</uni-forms-item>

							<uni-forms-item name="password" required>
								<uni-easyinput type="password" v-model="userForm.password" placeholder="请输入密码" />
							</uni-forms-item>

							<view class="xieyi_user" style="margin-bottom: 46rpx;margin-top: -20rpx;">
								<!-- 勾选协议 -->
								<view class="xieyi_password">
									<uni-data-checkbox v-model="radio" :localdata="range" @change="xieyiChange">
									</uni-data-checkbox>
								</view>
							</view>
						</uni-forms>
						<!-- 登录提交 -->
						<view class="submit-layer">
							<view class="login_btn phone_btn">
								登录
								<button class="control-button" @click="userFormSubmit"></button>
							</view>
							<view class="login_btn number_btn" @tap="loginSwitch(1)">返 回</view>
						</view>
					</template>

					<form @submit="phoneFormSubmit" :style="'display: ' + 
                    	(loginSwitchType == 2 ? 
                    	'block' : 
                    	'none')">
						<van-cell-group :border="false">
							<!-- 手机号 -->
							<van-field clearable id="phoneNumber" :data-rules="{
                    					required: true,
                    					number: true,
                    					minlength: 11,
                    					maxlength: 11,
                    					tel: true
                    				}" :rulesMsg="{
                    					required: '手机号码不能为空',
                    					number: '手机号码只能为数字',
                    					minlength: '手机号码最少11位数',
                    					maxlength: '手机号码最多11位数',
                    					tel: '手机号码不正确'
                    				}" name="phoneNumber" title-width="60px" type="number" label="手机号" placeholder="请输入手机号"
								:error-message="phoneNumberError" maxlength="11" :border="true"
								@input="phoneNumberInput()" />
							<!-- 验证码登录 -->
							<van-field clearable id="smsCode" :data-rules="{
                    				required: true,
                    				number: true,
                    				minlength: 6,
                    				maxlength: 6
                    				}" :rulesMsg="{
                    				required: '验证码不能为空',
                    				number: '验证码只能为数字',
                    				minlength: '验证码最少6位',
                    				maxlength: '验证码最多6位数'
                    				}" name="smsCode" type="number" placeholder="请输入验证码" :error-message="smsCodeError"
								maxlength="6" :border="true" @input="smsCodeInput()" use-button-slot>
								<van-button plain slot="button" size="small" type="danger" @click="getSmsCode"
									:disabled="smsCodeBtn">
									{{ smsCodeTimes }}{{ smsCodeText }}
								</van-button>
							</van-field>
						</van-cell-group>
						<!-- 登录提交 -->
						<view class="submit-layer">
							<van-button block round type="danger">
								登录
								<button class="control-button" form-type="submit"></button>
							</van-button>
							<view style="margin-top: 10px">
								<van-button block round color="#323233" plain @click="loginSwitch(1)">
									返 回
								</van-button>
							</view>
						</view>
					</form>
					<!-- 勾选协议 -->
					<view class="xieyi" v-if="loginSwitchType != 3">
						<uni-data-checkbox v-model="radio" :localdata="range" @change="xieyiChange"></uni-data-checkbox>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getImage,
		getPage
	} from '../../utils/config';
	import {
		promisify,
		$empty,
		storage,
		$toast,
		http,
		Validate
	} from '../../utils/utils';
	import wxApi from '../../utils/wxApi';
	import api from '../../utils/api';
	const app = getApp();
	export default {
		data() {
			return {
				guid: '',
				scene: {},
				logged: 0,

				//判断是否登录 0未登录 1已登录
				logoImg: getImage.logo,

				qudao: '',
				click_id: '',

				wechatImg: getImage.wechat,
				pwIcon: 'eye-o',
				pwType: false,
				smsCode: '',
				checked: true,
				smsCodeBtn: false,
				smsCodeText: '获取验证码',
				loginSwitchType: 1,
				loginSwitchText: '账号密码登录',
				list: {},
				radio: 0,

				userForm: {
					userName: '',
					password: ''
				},

				//phoneForm
				phoneForm: {
					phoneNumber: '',
					smsCode: ''
				},

				localInfo: '',
				userId: '',
				userRank: '',
				bgurl: '',
				userNameError: '',
				passwordError: '',
				phoneNumberError: '',
				smsCodeError: '',
				smsCodeTimes: '',
				session_key: '',
				openid: '',
				modalstatus: false,
				navbar: {},
				isShowPlayButton: false,
				range: [{
					"value": 1,
					"text": "请阅读并同意可居用户服务协议"
				}],
				rules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空',
						}]
					},
					password: {
						rules: [{
								required: true,
								errorMessage: '密码不能为空',
							},
							{
								minLength: 6,
								maxLength: 20,
								errorMessage: '密码长度在 6 到 20 个字符',
							}
						]
					}
				}
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad(options) {
			storage.get('qudao')
				.then((res) => {
					// 渠道进来
					console.log('quddddddddddddddd===', res);
					this.setData({
						qudao: res
					});
				})
				.catch((err) => {
					console.log('errrrrrrrrrrrrrrr', err);
				});
			storage.get('click_id')
				.then((res) => {
					// 渠道进来
					console.log('clickiiiiiiiiiiiiiiii===', res);
					this.setData({
						click_id: res
					});
				})
				.catch((err) => {
					console.log('errrrrrrrrrrrrrrr', err);
				});
			const scene = decodeURIComponent(options.scene);
			// if (app.pid > 0) {
			//   //pid = app.pid;
			//   console.log(app.pid)
			// } else {
			//   app.pid = 10;

			// }
			if (options.scene) {
				const array = scene.split('=');
				if (array[0] == 'guid') {
					this.guid = array[1]
				}
			}
			console.log(this.guid);
			/**
			 * 页面参数
			 */
			if (JSON.stringify(options) !== '{}') {
				if (options.guid) {
					this.guid = options.guid
					console.log(options.guid);
				}
			}

			//获取system信息
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				// #ifdef MP-WEIXIN
				this.navbar = uni.getMenuButtonBoundingClientRect()
				console.log("--------------", this.navbar)
				// #endif

				//获取右上角胶囊信息
				// #ifdef MP-TOUTIAO
				let navbar = uni.getMenuButtonBoundingClientRect()
				let CustomButton = tt.getCustomButtonBoundingClientRect()
				navbar.customWidth = CustomButton.customNavigation.width - 10
				navbar.marginLeft = CustomButton.customNavigation.marginLeft + 5
				this.navbar = navbar
				// #endif

				// #ifdef APP-PLUS
				this.navbar = menuButton
				// #endif
				this.window = res
			});

			//判断是否登录
			app.globalData
				.getLogin()
				.then((res) => {
					this.logged = res;
					this.localInfo = res;
					this.userId = res.data.user.user_id;
					this.userRank = res.data.user.user_rank;
					console.log(this.userId);
					if (options.web) {
						//网页自动登录
						wxApi.navigateTo('/pages/web/web?id=https://m.zhiai888.com/badun/login/' + this.userId);
					} else if (res.data.user.user_id > 0) {
						wxApi.navigateBack(1);
					}
				})
				.catch((res) => {
					this.logged = res
				});

			//获取协议地址
			http.get(
				api.default, {
					data: {
						action: 'getreginfo'
					}
				},
				false
			).then((res) => {
				const {
					data
				} = res.data;
				console.log(data);
				this.list = data.data;
				this.bgurl = data.bgurl;
			});
			this.wxlogin();
		},

		/**
		 * 右上角分享事件
		 */
		onShareAppMessage(res) {},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {
			this.videoContext = uni.createVideoContext('myVideo');
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			uni.hideHomeButton();
			uni.hideShareMenu({
				success: (res) => {}
			});
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {},
		methods: {

			async getUserProfile() {
				if (this.radio != 1) return $toast("请勾选同意用户服务协议");
				let that = this
				let obj = {}
				var pid = 0;
				if (app.globalData.pid > 0) {
					pid = app.globalData.pid;
				}
				uni.login({ //uni,tt 都行
					force: true,
					provider: 'toutiao',
					success: function(loginRes) {
						console.log('loginRes=========', loginRes) //获取code
						that.code = loginRes.code
						that.anonymous_code = loginRes.anonymousCode
					}
				})
				uni.getUserProfile({
					success: (res) => {
						console.log('uuuuuuuinfo=>', res)
						if (that.code) {
							obj = { //组装后台登录接口所需数据
								action: 'loginfromdouyin',
								code: that.code,
								anonymous_code: that.anonymous_code,
								nickname: res.userInfo.nickName,
								avatarUrl: res.userInfo.avatarUrl,
								city: res.userInfo.city,
								province: res.userInfo.province,
								sex: res.userInfo.gender,
								pid: pid,
							}
						}
						if (that.qudao) {
							obj.qudao = that.qudao;
						}
						if (that.click_id) {
							obj.click_id = that.click_id;
						}
						uni.setStorageSync('authInfo', res.userInfo);
						if (res) {
							that.loginF(obj) //调用登录接口
						}
					},
					fail: (err) => {
						console.log('err', err);
						uni.showModal({
							title: '提示',
							content: JSON.stringify(err),
							success: function(res) {
								if (res.confirm) {

								} else if (res.cancel) {

								}
							}
						});

					}
				})
			},

			async loginF(obj) { //登录接口
				console.log('ooooooooooobj=>', obj)
				http.post(api.default, {
					data: obj
				}).then((res) => {
					const {
						data
					} = res.data;
					if (res.data.code == 0) {
						console.log(data);
						//登录成功存储用户信息
						app.globalData.setLogon(data, 1, () => {
							//登录后跳转

							$toast(`登录成功`, {
								icon: 'success',
								times: 1000
							}).then(() => {
								if (data.bindwx == 1) {
									wxApi.navigateTo(getPage.wx +
										'?uid=' + data.user.user_id
									);
								} else {
									console.log('switchTab--------------------')
									setTimeout(() => {
										wxApi.switchTab(getPage.home)
									}, 1000)
								}
								//wxApi.refreshPage();
							});
						});
					} else {
						$toast(res.errmsg);
					}
				});
			},

			/**
			 * 手机注册
			 */
			gom() {
				wxApi.navigateTo(getPage.reguser + '?guid=' + this.guid);
			},

			xieyiChange(e) {
				console.log('勾选eeeeeeeeeeee··············', e)
				this.checked = e.detail.value;
			},

			/**
			 * 切换登录方式
			 */
			loginSwitch(ind) {
				this.loginSwitchType = ind
			},

			/**
			 * 密码切换显示
			 */
			pwChange() {
				/* ---处理dataset end--- */
				if (this.pwType) {
					this.pwIcon = 'eye-o';
					this.pwType = false
				} else {
					this.pwIcon = 'closed-eye';
					this.pwType = true
				}
			},

			showdingyue() {
				uni.requestSubscribeMessage({
					tmplIds: ['TOqslhth-Mi9dZCm6xzdFDq0dsLdA91jxiF8qoFaebU'],
					success(res) {}
				});
			},

			/**
			 * 用户名/密码登录提交form
			 */
			userFormSubmit(form) {
				this.$refs.userFormRef.validate().then(res => {
					console.log('表单数据信息：', res);
					if (this.checked) {

						let {
							userName,
							password
						} = res;
						http.post(api.default, {
							data: {
								action: 'login_guid',
								username: userName,
								guid: password
							}
						}).then((res) => {
							const {
								data
							} = res.data;
							if (res.data.code == 0) {
								//登录成功存储用户信息
								app.globalData.setLogon(data, 1, () => {
									//登录后跳转
									$toast(`登录成功`, {
										icon: 'success',
										times: 1000
									}).then(() => {
										if (data.bindwx == 1) {
											wxApi.navigateTo(getPage.wx + '?uid=' + data
												.user.user_id);
										} else {
											wxApi.switchTab(getPage.home);
										}
										//wxApi.refreshPage();
									});
								});
							} else {
								$toast(res.errmsg);
							}
						});
					} else {
						$toast('请勾选同意以下协议');
					}
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},


			/**
			 * 手机号码 input
			 */
			phoneNumberInput(event, _dataset) {
				this.phoneNumberError = ''
				this.phoneForm.phoneNumber = $empty(event.detail)
			},

			/**
			 * 手机短信验证码 input
			 */
			smsCodeInput(event, _dataset) {
				this.smsCodeError = ''
				this.phoneForm.smsCode = $empty(event.detail)
			},

			/**
			 * 手机号/短信码登录 form
			 */
			phoneFormSubmit(e) {
				const {
					value
				} = e.detail;
				const {
					logged,
					phoneForm
				} = this;
				Validate.check(this, this.phoneValidate, value, (res) => {
					if (!res && !logged) {
						return false;
					}
					var pid = 0;
					if (app.globalData.pid > 0) {
						pid = app.globalData.pid;
					}
					//判断是否登录
					http.post(api.default, {
						data: {
							action: 'login_msg',
							mobile: phoneForm.phoneNumber,
							code: phoneForm.smsCode,
							pid: pid,
							guid: this.guid
						}
					}).then((res) => {
						const {
							data
						} = res.data;
						if (res.data.code == 0) {
							//登录成功存储用户信息
							app.globalData.setLogon(data, 1, () => {
								//登录后跳转
								$toast(`登录成功`, {
									icon: 'success',
									times: 1000
								}).then(() => {
									if (data.bindwx == 1) {
										wxApi.navigateTo(getPage.wx + '?uid=' + data.user
											.user_id);
									} else {
										wxApi.switchTab(getPage.home);
									}
									//wxApi.refreshPage();
								});
							});
						} else {
							$toast(res.errmsg);
						}
						// if (data.bindwx == 0) {
						//   //登录成功存储用户信息
						//   app.setLogon(data, 1, () => {
						//     //登录后跳转

						//     $toast(`登录成功`, {
						//       icon: 'success',
						//       times: 1000,
						//     }).then(() => {
						//       wxApi.refreshPage();
						//     })
						//   });
						// } else {
						//   //跳转绑定微信
						//   wxApi.navigateTo(getPage.wechat, {
						//     id: data.user.user_id
						//   });
						// }
					});
				});
			},

			/**
			 * 获取手机验证码
			 */
			getSmsCode() {
				const {
					phoneNumber
				} = this.phoneForm;
				Validate.rules('#phoneNumber', (res) => {
					Validate.check(
						this,
						res, {
							phoneNumber: phoneNumber
						},
						(rs, err) => {
							if (!rs) {
								$toast(err[0].msg);
								return false;
							}
							http.post(api.default, {
								data: {
									action: 'login_sms',
									mobile: phoneNumber
								}
							}).then((res) => {
								var times = 60;
								var countInter = setInterval(() => {
									if (times >= 1) {
										times--;
										this.smsCodeTimes = times;
									} else {
										/**
										 * 获取过期
										 */
										this.smsCodeBtn = false;
										this.smsCodeText = '重新获取';
										this.smsCodeBtn = '';
										clearInterval(countInter);
									}
								}, 1000);
								this.smsCodeBtn = true;
								this.smsCodeText = '秒后重发';
								this.smsCodeTimes = 60;
								//提示短信发送成功
								$toast('短信发送成功，请注意查收');
							});
						},
						false
					);
				});
			},

			/**
			 * 跳转重置密码
			 */
			goPagesReset() {
				wxApi.navigateTo(getPage.reset);
			},

			wxlogin() {
				//获取用户的openID和sessionKey

				var that = this;
				uni.login({
					//获取code 使用wx.login得到的登陆凭证，用于换取openid
					success: (res1) => {
						console.log(res1);
						http.post(api.default, {
							data: {
								action: 'getweixininfo',
								code: res1.code
							}
						}).then((res) => {
							this.session_key = res.data.data.session_key;
							this.openid = res.data.data.openid;
						});
					}
				});
			},

			noSelectRadio() {
				return $toast("请勾选同意用户服务协议");
			},

			getPhoneNumber(e) {
				//点击获取手机号码按钮
				console.log('手机号~~~~~~~~~', e)
				var that = this;
				var guid = that.guid;
				var pid = 0;
				//$toast(app.pid)
				if (app.globalData.pid > 0) {
					pid = app.globalData.pid;
				}
				console.log('that.radio', that.radio)
				if (that.radio == 1) {
					//$toast("app.pid=" + app.pid + "，pid=" + pid);
					uni.checkSession({
						success: function() {
							console.log(that);
							var session_key = that.session_key;
							var openid = that.openid;
							if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
								this.modalstatus = true
							} else {
								//同意授权
								let parms = {
									action: 'GetWXPhoneNumber',
									guid: guid,
									openid: openid,
									session_key: session_key,
									aesIv: e.detail.iv,
									encryptedData: e.detail.encryptedData,
									pid: pid
								};
								if (that.qudao) {
									parms.qudao = that.qudao;
								}
								if (that.click_id) {
									parms.click_id = that.click_id;
								}
								//同意授权
								http.post(api.default, {
									data: parms
								}).then((res) => {
									const {
										data
									} = res.data;
									if (res.data.code == 0) {
										console.log(data);
										//登录成功存储用户信息
										app.globalData.setLogon(data, 1, () => {
											//登录后跳转

											$toast(`登录成功`, {
												icon: 'success',
												times: 1000
											}).then(() => {
												if (data.bindwx == 1) {
													wxApi.navigateTo(getPage.wx +
														'?uid=' + data.user.user_id
													);
												} else {
													wxApi.switchTab(getPage.home);
												}
												//wxApi.refreshPage();
											});
										});
									} else {
										$toast(res.errmsg);
									}
								});
							}
						},
						fail: function() {
							$toast('session_key 已经失效，需要重新执行登录流程');
							that.wxlogin(); //重新登录
						}
					});
				} else {
					$toast('请勾选同意用户服务协议');
					return false;
				}
			},

			gohome() {
				wxApi.switchTab(getPage.home);
			},

			onPlay(e) {
				this.isShowPlayButton = true
				this.videoContext.play();
			},

			ended(e) {
				// console.log('ended', e);
				this.isShowPlayButton = false
			}
		}
	};
</script>
<style>
	@import './login.css';
</style>
